<template>
  <div class="main-container">
    <el-row>
      <el-button type="primary" @click="addRole()">添加角色</el-button>
      <el-button type="primary" @click="create()">刷新</el-button>
    </el-row>
    <br />
    <el-row>
      <el-col :span="10">
        <el-table :data="roleList" border>
          <el-table-column type="index" label="序号" align="center" width="50"></el-table-column>
          <el-table-column prop="roleName" label="角色" align="center" min-width="100"></el-table-column>
          <el-table-column label="用户" min-width="150">
            <template slot-scope="scope">
              <div v-for="item in scope.row.users" :key="item.jobNumber">{{ item.jobNumber }} - {{ item.userName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="250">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="modifyRole(scope.row)">修改</el-button>
              <el-button size="mini" type="danger" @click="removeRole(scope.row)">删除</el-button>
              <el-button size="mini" type="primary" @click="authorityCheckInit(scope.row)">权限变更</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="8" :offset="1">
        <!-- 角色权限设置区域 -->
        <div v-if="checkAuthorityVisible">
          <el-button type="warning">{{ this.currentRole.roleName }}</el-button>
          <el-button type="primary" @click="saveRoleAuthority()">保存</el-button>
          <el-button type="primary" @click="resetChange()">重置</el-button>
          <el-button @click="cancelChange()">取消</el-button>
          <br />
          <el-form>
            <el-form-item v-for="(item, index) in Object.keys(authorityCheckList)" :key="index">
              <div class="mb10 fontSize16 bold">{{ item }}</div>
              <span v-for="authority in authorityCheckList[item]" :key="authority.authorityId" class="mr20">
                <el-checkbox v-model="authority.selected" :label="authority.authorityName"></el-checkbox>
              </span>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { Message, Notification } from 'element-ui'
import _ from 'lodash'

// 权限模块接口
import { getRoleListApi, getAuthorityListApi, addRoleApi, modifyRoleNameApi, removeRoleApi, saveRoleAuthorityApi } from '@/api/authority/api-authority'

@Component({})
export default class RoleManager extends Vue {
  /***********************************************************************
   * 页面初始化 ***********************************************************
   *********************************************************************** */
  create() {
    this.getRoleList()
    this.getAuthorityist()
  }

  // 系统角色列表
  roleList: any = []
  // 系统权限列表
  authorityList: any = []

  // 获取系统角色列表
  async getRoleList() {
    await getRoleListApi({ rich: true })
      .catch(err => Notification.error(err))
      .then((res: any) => (this.roleList = res.data))
  }
  // 获取系统权限列表
  async getAuthorityist() {
    await getAuthorityListApi({ rich: false })
      .then((res: any) => (this.authorityList = res.data))
      .catch(err => Notification.error(err))
  }

  /*************
   * 页面初始化 *
   *********** */
  /*************************************************************************
   * 角色管理功能：添加/修改/删除 ********************************************
   *********************************************************************** */

  // 新建角色
  addRole() {
    this.$prompt('请输入新建角色的名称：', '新建角色', {
      confirmButtonText: '保存',
      cancelButtonText: '取消'
    }).then((value: any) => this.addRoleReq(value.value))
  }
  async addRoleReq(roleName) {
    let param = {
      roleId: null,
      roleName: roleName
    }
    await addRoleApi(param)
      .then(() => this.getRoleList())
      .catch(err => Notification.error(err))
  }

  // 修改角色：即修改角色名称
  modifyRole(role) {
    this.$prompt('请输入修改角色的名称：', '修改角色', {
      confirmButtonText: '保存',
      cancelButtonText: '取消'
    }).then((value: any) => {
      let param = {
        roleId: role.roleId,
        roleName: value.value
      }
      this.modifyRoleNameReq(param)
    })
  }
  async modifyRoleNameReq(role) {
    await modifyRoleNameApi(role)
      .then(() => this.getRoleList())
      .catch(err => Notification.error(err))
  }

  // 删除角色
  removeRole(role) {
    this.$confirm('请确认删除角色：' + role.roleName, '删除角色', {
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    }).then(() => this.removeRoleReq(role.roleId))
  }
  async removeRoleReq(roleId) {
    await removeRoleApi({ roleId: roleId })
      .then(() => this.getRoleList())
      .catch(err => Notification.error(err))
  }

  /******************************
   * 角色管理功能：添加/修改/删除 *
   **************************** */
  /***********************************************************************
   * 角色权限管理 *********************************************************
   *********************************************************************** */
  // 角色权限修改区域可见控制
  checkAuthorityVisible: boolean = false

  // 角色权限修改区域绑定数据
  authorityCheckList: any = {}

  // 当前变更权限的角色
  currentRole: any = {}

  authorityCheckInit(role) {
    // 暂存当前设置权限的角色对象
    this.currentRole = role
    // 当前角色已有权限绑定
    let tempAuthorityList = this.authorityList
    tempAuthorityList = tempAuthorityList.map(item => {
      if (this.currentRole.authorityIds.indexOf(item.authorityId) != -1) {
        this.$set(item, 'selected', true)
      } else {
        this.$set(item, 'selected', false)
      }
      return item
    })
    // 按照权限对象分组
    this.authorityCheckList = {}
    for (let i = 0; i < tempAuthorityList.length; i++) {
      let authority = tempAuthorityList[i]
      if (Object.keys(this.authorityCheckList).indexOf(authority.authorityObj) == -1) {
        this.authorityCheckList[authority.authorityObj] = []
      }
      this.authorityCheckList[authority.authorityObj].push(authority)
    }
    // 权限设置区域可见
    this.checkAuthorityVisible = true
  }

  // 保存角色权限设置
  saveRoleAuthority() {
    let selectedAuthority: any = []
    for (let key in this.authorityCheckList) {
      this.authorityCheckList[key]
        .filter(item => item.selected)
        .map(item => item.authorityId)
        .forEach(item => {
          selectedAuthority.push(item)
        })
    }
    let params = {
      roleId: this.currentRole.roleId,
      authorityIds: selectedAuthority
    }
    this.$confirm('请确认：角色权限的修改将同步影响该角色用户的权限', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    }).then(() => this.saveRoleAuthorityReq(params))
  }
  async saveRoleAuthorityReq(param) {
    await saveRoleAuthorityApi(param)
      .then(() => {
        this.getRoleList()
        this.cancelChange()
      })
      .catch(err => Notification.error(err))
  }

  // 重置角色权限设置
  resetChange() {
    this.authorityCheckInit(this.currentRole)
  }

  // 取消角色权限设置
  cancelChange() {
    this.checkAuthorityVisible = false
    this.authorityCheckList = {}
    this.currentRole = {}
  }

  /***************
   * 角色权限管理 *
   ************* */
  /*************************************************************************
   *************************************************************************
   *********************************************************************** */
}
</script>

<style lang="scss" scoped>
</style>
